import time
import threading
from time import sleep
import uiautomation as auto
from uiautomation import WindowControl, ControlType
import time
# from rule import *
import pyperclip
import subprocess
import re
import openpyxl
import pandas as pd
from datetime import datetime
from queue import Empty
from threading import Thread
# from wcferry import Wcf, WxMsg
import time
import requests
import json
from pymongo import MongoClient
import pymongo
from pymongo.errors import PyMongoError
# from bson import json_util as jsonb
# import pymongo
# from pymongo import MongoClient
auto.uiautomation.TIME_OUT_SECOND = 10
wins = auto.DocumentControl(ClassName='Chrome_RenderWidgetHostHWND', Name="移动办公")
# 存储结构，用于存储被选中的群成员
mention_member = {}
execution_count = {}
# 锁，用于线程安全地访问mention_member
lock = threading.Lock()
# 连接到 MongoDB 数据库
client = MongoClient('mongodb://localhost:27017/')  # 根据实际情况修改连接地址
db = client['test1']  # 数据库名称
collection = db['test1']
collection2 = db.watest1
# def connection():
#     # 1:连接本地MongoDB数据库服务
#     conn = MongoClient("localhost", 27017)
#     # conn.admin.authenticate("zhangchun", "Zc@123123")
#     # 2:连接本地数据库(guazidata)。没有时会自动创建
#     db = conn.test1
#     # 3:创建集合
#     set1 = db.test1
#     return set1

class GroupMember:
    def __init__(self, groupid, id):
        self.groupid = groupid
        self.id = id

def get_weather(msg):##气象小专家智能体
    try:
        # for x in agent.find({"AppName": "气象小专家"}):
        #     Token = x.get("Token")
        #     appId = x.get("应用ID")
        #     url = x.get("url")
        Token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsInNpZ25fdHlwZSI6IlNJR04ifQ.eyJhcGlfa2V5IjoiNjc4ODY0ODgxNWU1MTIxMjg3Y2JjMmRjIiwiZXhwIjoxNzM5MDA3NDcwLCJ0aW1lc3RhbXAiOjE3Mzg2NDc0NzB9.87VaFFLuVx7BPCpbPSdBswU5cjg5MXCVgLQWyDzw43s"
        appId = "6783255adafcea4fea2945f4"
        url = "https://jiutian.10086.cn/largemodel/api/v2/completions"
    except Exception as e:
        print(e,13323)
    try:
        print("来自天气智能体收到：{}".format(msg))
        AuthorizationMsg = "Bearer {}".format(Token)
        # 定义请求的URL和头部信息
        headers = {
            "Content-Type": "application/json",
            "Authorization": AuthorizationMsg
        }
        # 定义请求的数据
        data = {
            "model": "jiutian-lan",
            "prompt": msg,
            "temperature": 0.1,
            "top_p": 0.1,
            "history": [],
            "appId": appId,
            "stream": False
        }
        # 发送POST请求
        response = requests.post(url, headers=headers, data=json.dumps(data))
        # 将JSON字符串解析为Python字典
        parsed_data = json.loads(response.text)
        # 提取所需的文本
        desired_text = parsed_data['choices'][0]['text']
        # print(desired_text)
        return desired_text
    except Exception as e:
        print(e,13350)

def add_member(groupid, id):
    """添加群成员到存储结构，并初始化参数b和c，记录开始时间"""
    with lock:
        key = (groupid, id)
        mention_member[key] = {'b': 1, 'c': 0, 'start_time': time.time()}
        # 可以启动一个单独的线程来检查这个成员的状态（这里为了简化不启动线程）


def reply_received(groupid, id):
    """当群成员回复收到时，将参数b设置为0"""
    with lock:
        key = (groupid, id)
        if key in mention_member:
            mention_member[key]['b'] = 0


def check_members():
    """定期检查群成员的状态，当b和c同时为1时输出groupid和id"""
    while True:
        with lock:
            current_time = time.time()
            for key, member in mention_member.items():
                groupid, id = key
                if key not in execution_count:
                    execution_count[key] = 0
                if member['b'] == 1 and member['c'] == 0 and current_time - member['start_time'] > 20 and execution_count[key] < 3:
                    member['c'] = 1
                    if member['b'] == 1 and member['c'] == 1:
                        print(f"Group ID: {groupid}, Member ID: {id}")
                        yidong = yidongOffice()
                        yidong.findGroup(groupid)
                        yidong.sendMsg("请注意查收消息，@机器人回复收到将停止督办", id, "是", "群聊")
                        yidong.findGroup("我的文件助手")
                        member['start_time'] = current_time
                        member['c'] = 0
                        execution_count[key] += 1
                # elif member['b'] == 1 and member['c'] == 1:
                #     print(f"Group ID: {groupid}, Member ID: {id}")
                #     yidong = yidongOffice()
                #     yidong.findGroup(groupid)
                #     yidong.sendMsg("请注意查收消息", id, "是", "群聊")
                #     yidong.findGroup("我的文件助手")

                        # 可以选择从mention_member中移除这个成员，或者做其他处理
                        # del mention_member[key]  # 如果要移除成员，取消注释这行代码
        # 为了避免过于频繁地检查，添加一个小延迟
        time.sleep(10)


# 启动检查成员的线程
checker_thread = threading.Thread(target=check_members)
checker_thread.daemon = True  # 设置为守护线程，这样主程序结束时它也会自动结束
checker_thread.start()

# 示例使用
# add_member("数字机器人测试", "张晓明")  # 添加一个群成员
# 这里应该模拟等待群成员回复，但在实际脚本中，这个调用会来自其他事件（如网络请求）
# 由于我们是在脚本中运行，没有模拟等待，所以c会直接因为超时变为1，而b仍然是1（因为没有调用reply_received）
# 在实际应用中，你会在收到群成员回复时调用reply_received函数

# 注意：这个脚本会一直运行，直到你手动停止它（例如，通过Ctrl+C）。
# 在实际应用中，你可能需要一种机制来优雅地停止脚本，比如监听一个特定的信号或事件。

class yidongOffice():
    def findGroup(self, name):
        try:
            groupName = wins.TextControl(Name=name)
            groupName.Click()
            print(26)
            msgadd = wins.ListControl().GetChildren()[1].GroupControl(Depth=2).GetChildren()[2].GroupControl(
                Depth=1).GetChildren()
            msgadd[3].TextControl().Click()
        except Exception as e:
            print(e, 30)

    def findName(self, name):
        try:
            personName = wins.TextControl(Name=name)
            personName.Click()
            editFind = wins.EditControl(Name="搜索")
            time.sleep(1)
            editFind.SendKeys(name)
            listItemFind = wins.ListItemControl(Name=name)
            listItemFind.Click()
        except Exception as e:
            print(e, 42)

    def sendMsg(self, msg, at, isSMS, chatType):  # 消息内容,@人名,是否短信提醒：是或者否，私聊或者群聊
        try:
            msgadd = wins.ListControl().GetChildren()[1].GroupControl(Depth=2).GetChildren()[2].GroupControl(
                Depth=1).GetChildren()
            msgadd[3].TextControl().Click()
            pyperclip.copy(msg + "@")
            msgadd[3].TextControl().SendKeys('{Ctrl}v')
            if at != "" and chatType != "私聊":  ##群聊@
                try:
                    msgadd[3].TextControl().SendKeys("{}".format(at))
                    msgadd[3].TextControl().SendKeys('{Enter}')
                except Exception as e:
                    print(e)
            msgadd[3].TextControl().SendKeys('{Enter}')
            if isSMS == "是" and chatType == "群聊":  # 群聊短信提醒
                smsAt = msgadd[3].TextControl(Name="@{}".format(at))
                smsAt.Click()
                smsSend = msgadd[3].TextControl(Name="发送短信提醒")
                smsSend.Click()
                msgadd[3].TextControl().SendKeys('{Enter}')
            if isSMS == "是" and chatType == "私聊":  # 私聊短信提醒
                smsAt = msgadd[3].TextControl(Name=msg)
                smsAt.RightClick()
                smsSend = msgadd[3].TextControl(searchDepth=5, Name="短信提醒")
                smsSend.Click()
                msgadd[3].TextControl().SendKeys('{Enter}')
        except Exception as e:
            print(e, 69)


def getContact(who):
    try:
        win = auto.DocumentControl(
            ClassName='Chrome_RenderWidgetHostHWND', Name="移动办公")
        conlist0 = wins.ListItemControl().GroupControl(Depth=2).GetChildren()
        conlist = conlist0[1].GetChildren()
        vision = []
        for con in conlist:
            conn = con.GetChildren()[2].TextControl()
            vision.append(conn.IsOffscreen)
            if conn.Name == who:  # 在当前列表
                if conn.IsOffscreen == 0:  # 在屏幕显示范围内
                    conn.Click()
                    wins.ListControl().GetChildren()[1].GroupControl(
                        Depth=2).GetChildren()[2].Click()
                    return con.AutomationId[6:8]
                else:  # 在屏幕显示范围外
                    if 0 in vision:  # 在当前屏幕下方
                        while (conn.IsOffscreen):  # 在显示范围内，停止滚动鼠标
                            conlist0[0].WheelDown(wheelTimes=3, waitTime=0.1)
                            sleep(0.1)
                        conn.Click()
                        wins.ListControl().GetChildren()[1].GroupControl(
                            Depth=2).GetChildren()[2].Click()
                        return con.AutomationId[6:8]
                    else:  # 在当前屏幕上方
                        while (conn.IsOffscreen):  # 在显示范围内，停止滚动鼠标
                            conlist0[0].WheelUp(wheelTimes=3, waitTime=0.1)
                            sleep(0.1)
                        conn.Click()
                        wins.ListControl().GetChildren()[1].GroupControl(
                            Depth=2).GetChildren()[2].Click()
                        return con.AutomationId[6:8]
        # 不在当前列表
        wins.EditControl(name='搜索').SendKeys(who, waitTime=2)
        wins.ListItemControl().GetChildren()[1].Click(waitTime=1.5)
        conn1 = wins.ListItemControl().GroupControl(
            Depth=2).GetChildren()[1].GetChildren()[0]
        if conn1.GetChildren()[2].TextControl().Name == who:
            wins.ListControl().GetChildren()[1].GroupControl(
                Depth=2).GetChildren()[2].Click()
            return conn1.AutomationId[6:8]
        else:
            print('NO')
    except Exception as e:
        print(e)


def sedMsg(content):
    try:
        win = auto.DocumentControl(
            ClassName='Chrome_RenderWidgetHostHWND', Name="移动办公")
        msgadd = wins.ListControl().GetChildren()[1].GroupControl(Depth=2).GetChildren()[2].GroupControl(
            Depth=1).GetChildren()
        msgadd[3].TextControl().Click()
        pyperclip.copy(content)
        msgadd[3].TextControl().SendKeys('{Ctrl}v')
        msgadd[3].TextControl().SendKeys('{Enter}')
    except Exception as e:
        print(e, 129)


def sedFile(path):
    try:
        # subprocess.Popen(r'C:\Program Files (x86)\China Mobile\yidongbangong\yidongbangong.exe')
        win1 = auto.DocumentControl(ClassName='Chrome_RenderWidgetHostHWND', Name="移动办公").ListControl().GetChildren()[1]
        win1.GroupControl(Depth=2).GetChildren()[2].GroupControl(Depth=1).GetChildren()[2].GetChildren()[1].Click()
        win2 = auto.WindowControl(ClassName='#32770', Name="选择文件").EditControl(Name='文件名(N):')
        time.sleep(2)
        pyperclip.copy(path)
        win2.SendKeys('{Ctrl}v')
        # win2.SendKeys(path)
        win2.SendKeys('{Enter}')
    except Exception as e:
        print(e, 125)


def getNewmsgv2(who=''):
    try:
        win = auto.DocumentControl(
            ClassName='Chrome_RenderWidgetHostHWND', Name="移动办公")
        msgcnt = wins.ListControl().GetChildren()[1].GetChildren()[0].GetChildren()[0].GetChildren()[1].GetChildren()[
            -2].GetChildren()
        person = ''
        content = ''
        msgtype = ''
        con = ''
        groupname = ''
        # flag = 0
        msgn = msgcnt[-2].GetChildren()[-1].GetChildren()
        if len(msgn) in (3, 4):
            person = msgn[1].Name
            if len(msgn[2].GetChildren()[0].GetChildren()[0].GetChildren()) == 3:
                content = msgn[2].GetChildren()[0].GetChildren()[
                    0].GetChildren()[1].Name
                msgtype = '文件'
            elif msgn[2].GetChildren()[0].GetChildren()[0].GetChildren()[0].ControlType == 50006:
                content = msgn[2].GetChildren()[0].GetChildren()[0].GetChildren()[
                    0].LocalizedControlType
                msgtype = '图片'
            else:
                for i in msgn[2].GetChildren()[0].GetChildren()[0].GetChildren()[0].GetChildren():
                    if i.ControlType == 50026:
                        con = con + i.TextControl().Name
                    elif i.ControlType == 50020:
                        con = con + i.Name
                content = con
                msgtype = '文本'
        elif len(msgn) in (2, 3):
            if len(msgn) == 3:
                person = '本人'
            else:
                person = wins.ListControl().GetChildren()[1].TextControl().Name
            if len(msgn[1].GetChildren()[0].GetChildren()[0].GetChildren()) == 3:
                content = msgn[1].GetChildren()[0].GetChildren()[
                    0].GetChildren()[1].Name
                msgtype = '文件'
            elif msgn[1].GetChildren()[0].GetChildren()[0].GetChildren()[0].ControlType == 50006:
                content = msgn[1].GetChildren()[0].GetChildren()[0].GetChildren()[
                    0].LocalizedControlType
                msgtype = '图片'
            else:
                for i in msgn[1].GetChildren()[0].GetChildren()[0].GetChildren()[0].GetChildren():
                    if i.ControlType == 50026:
                        con = con + i.TextControl().Name
                    elif i.ControlType == 50020:
                        con = con + i.Name
                    elif i.ControlType == 50006:
                        con = con + i.Name
                content = con
                msgtype = '文本'
        # if '@' + who in content:
        #     flag = 1
        target_control = find_control_by_automation_id(wins, "group-name-span")
        # 检查是否找到了目标控件
        if target_control:
            # 对 target_control 进行操作
            print(f"找到了控件，Name: {target_control.Name}, ControlType: {target_control.ControlType}")
            group1 = target_control.GetChildren()
            groupname = group1[0].Name
            print(groupname)
            # ... 其他操作
        else:
            print("具有指定 AutomationId 的控件不存在")
        return person, content, msgtype, groupname
    except Exception as e:
        print(e)





def check_excel(content):
    try:
        df = pd.read_excel('楚雄有问有答机器人.xlsx')
    except FileNotFoundError:
        print("文件不存在")
        return

    if '套餐名称' not in df.columns:
        print("Excel文件中缺少'套餐名称'列")
        return

    matching_rows = df[df['套餐名称'] == content]

    if matching_rows.empty:
        print("没有相符项")
        return

    result_lines = []
    # 取第一个匹配的行
    row = matching_rows.iloc[0]
    for col_name, value in row.items():
        if pd.notna(value):
            result_lines.append(f"{col_name}：{value}")

    return '\n'.join(result_lines)


# 示例用法
# result = check_excel("测试套餐")
# if result:
#     print(result)

# 打开远程ToDesk
def openToDesk():
    try:
        result = subprocess.run(['d:\\desk\\ToDesk.exe'])
    except Exception as e:
        print(e)

# 退出远程ToDesk
def closeToDesk():
    try:
        result = subprocess.run(['d:\\desk\\closeDesk.exe'])
    except Exception as e:
        print(e)

def replyGroupMsg(person, content, groupname):
    try:
        if "督办@" in content:
            match = re.search(r'@(.*)', content)
            if match:
                result = match.group(1)  # group(1) 获取第一个捕获组的内容
                # print(result)
                words = result.split()
                cleaned_words = [part.strip() for part in words]
                # print(cleaned_parts[0])# 去除每个子字符串两端的空白字符
                atname, con2, = cleaned_words
                add_member(groupname, atname)
                yidong = yidongOffice()
                yidong.findGroup("我的文件助手")
                # yidong = yidongOffice()
                # yidong.findGroup(groupname)
                # yidong.sendMsg("开始督办", person, "是", "群聊")
                # con3 = "请注意查收此消息：" + con2
                # yidong.sendMsg(con3, atname, "是", "群聊")
            else:
                print("没有找到匹配项")
                yidong = yidongOffice()
                yidong.findGroup(groupname)
                yidong.sendMsg("执行失败", person, "是", "群聊")
                # yidong = yidongOffice()
                yidong.findGroup("我的文件助手")
        elif "楚雄明细表" in content or "双柏明细表" in content or "南华明细表" in content or "牟定明细表" in content or "禄丰明细表" in content or "大姚明细表" in content or "姚安明细表" in content or "永仁明细表" in content or "武定明细表" in content or "元谋明细表" in content:
            target1 = "明细"
            # 使用 find 方法找到第一个目标字符串的位置
            index1 = content.find(target1)
            # 如果找到了目标字符串，则提取它之前的所有字符
            lct1 = ""
            if index1 != -1:
                lct1 = content[:index1]
                print(lct1)
            else:
                print("未找到目标字符串")
            file = r'D:\yidonbangon\Digitalrobot\2024-12\xlsx文件\{}报障.xlsx'.format(lct1)
            sedFile(file)
            # yidong = yidongOffice()
            # yidong.findGroup("我的文件助手")
        elif "楚雄报障"in content or "双柏报障" in content or "南华报障" in content or "牟定报障" in content or "禄丰报障" in content or "大姚报障" in content or "姚安报障" in content or "永仁报障" in content or "武定报障" in content or "元谋报障" in content:
            # s = "客户经理姓名：何婷婷电话:13769297772"
            matchname = re.search(r"客户经理姓名：(.+?)客户经理电话", content)
            matchtel = re.search(r"客户经理电话：(.+?)客户名称", content)
            matchclient = re.search(r"客户名称：(.+?)联系人姓名", content)
            matchname2 = re.search(r"联系人姓名：(.+?)联系人电话", content)
            matchtel2 = re.search(r"联系人电话：(.+?)故障发生地址", content)
            matchlocation = re.search(r"故障发生地址：(.+?)产品实例标识", content)
            matchs = re.search(r"产品实例标识：(.+?)产品类型", content)
            matcht = re.search(r"产品类型：(.+?)故障描述", content)
            resultd = ""
            prefix = "故障描述："
            prefix_index = content.find(prefix)
            # 如果找到了前缀，则提取前缀之后的内容
            if prefix_index != -1:
                resultd = content[prefix_index + len(prefix):]
                # print(resultd)
            else:
                print("前缀未找到")
            # matchd = re.search(r"故障描述：(.+?)", content)
            # resultname, resulttel, resultclient, resultname2, resulttel2, resultlocation, results, resultt, resultd ="", "", "","", "", "","", "", ""
            resultname = matchname.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultname)
            resulttel = matchtel.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resulttel)
            resultclient = matchclient.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultclient)
            resultname2 = matchname2.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultname2)
            resulttel2 = matchtel2.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resulttel2)
            resultlocation = matchlocation.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultlocation)
            results = matchs.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(results)
            resultt = matcht.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultt)
            # resultd = matchd.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultd)
            # parts = content.strip().split('，')# 先去除字符串两端的空白字符，再以逗号为分隔符分解字符串
            # cleaned_parts = [part.strip() for part in parts]
            # # print(cleaned_parts[0])# 去除每个子字符串两端的空白字符
            # str1, str2, str3 = cleaned_parts
            # str11 = str1.replace("新增", "")
            # file_path = r'D:\pythonmini\testdata\{}明细.xlsx'.format(str11)  # 替换为你的Excel文件路径
            # wb = openpyxl.load_workbook(file_path)
            # ws = wb['Sheet1']
            # empty_row = None
            # for idx, cell in enumerate(ws['A'], start=1):  # 使用enumerate来获取行号，从1开始
            #     if cell.value is None:
            #         empty_row = idx
            #         break
            # if empty_row is None:
            #     empty_row = ws.max_row + 1
            # # 在A列的第一个空行单元格中输入数据
            # ws[f'A{empty_row}'] = str2
            # # 在B列中的相应行（即A列空行的右侧一个单元格）输入数据
            # ws[f'B{empty_row}'] = str3
            # # 保存更改
            # wb.save(file_path)  # 这将覆盖原始文件
            # # 如果你不想覆盖原始文件，可以保存到一个新文件
            # # wb.save('new_excel_file_with_data.xlsx')
            # print(f"数据已成功插入到A{empty_row}和B{empty_row}单元格中。")
            target = "报障"
            # 使用 find 方法找到第一个目标字符串的位置
            index = content.find(target)
            # 如果找到了目标字符串，则提取它之前的所有字符
            lct = ""
            if index != -1:
                lct = content[:index]
                print(lct)
            else:
                print("未找到目标字符串")
            current_datetime = datetime.now()
            # 格式化并打印当前时间
            mft_time = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
            file_path = r'D:\yidonbangon\Digitalrobot\2024-12\xlsx文件\{}报障.xlsx'.format(lct)  # 替换为你的Excel文件路径
            wb = openpyxl.load_workbook(file_path)
            ws = wb['Sheet1']
            empty_row = None
            for idx, cell in enumerate(ws['A'], start=1):  # 使用enumerate来获取行号，从1开始
                if cell.value is None:
                    empty_row = idx
                    break
            if empty_row is None:
                empty_row = ws.max_row + 1
            mftid = empty_row - 1
            # 在A列的第一个空行单元格中输入数据
            ws[f'A{empty_row}'] = mftid
            ws[f'B{empty_row}'] = resultname
            # 在B列中的相应行（即A列空行的右侧一个单元格）输入数据
            ws[f'C{empty_row}'] = resulttel
            ws[f'D{empty_row}'] = resultclient
            ws[f'E{empty_row}'] = resultname2
            ws[f'F{empty_row}'] = resulttel2
            ws[f'G{empty_row}'] = resultlocation
            ws[f'H{empty_row}'] = results
            ws[f'I{empty_row}'] = resultt
            ws[f'J{empty_row}'] = resultd
            ws[f'K{empty_row}'] = mft_time
            ws[f'L{empty_row}'] = "未处理"
            # 保存更改
            wb.save(file_path)  # 这将覆盖原始文件
            # 如果你不想覆盖原始文件，可以保存到一个新文件
            # wb.save('new_excel_file_with_data.xlsx')
            yidong = yidongOffice()
            yidong.findGroup(groupname)
            rpmsg = "已将信息写入表格，此故障序列号为：" + str(mftid)
            yidong.sendMsg(rpmsg, person, "是", "群聊")
            yidong.findGroup("我的文件助手")
            print(f"数据已成功插入单元格中。")

        elif "收到" in content:
            reply_received(groupname, person)
            yidong = yidongOffice()
            yidong.findGroup("我的文件助手")
            # yidong = yidongOffice()
            # yidong.findGroup(groupname)
            # yidong.sendMsg("", person, "是", "群聊")

        elif "楚雄故障处理情况"in content or "双柏故障处理情况" in content or "南华故障处理情况" in content or "牟定故障处理情况" in content or "禄丰故障处理情况" in content or "大姚故障处理情况" in content or "姚安故障处理情况" in content or "永仁故障处理情况" in content or "武定故障处理情况" in content or "元谋故障处理情况" in content:
            matchrid = re.search(r"故障序列号：(.+?)处理情况及进度", content)
            matchprc = re.search(r"处理情况及进度：(.+?)故障处理人", content)
            matchname3 = re.search(r"故障处理人：(.+?)是否宣贯10分满意", content)
            matchif10 = re.search(r"是否宣贯10分满意：(.+?)客户是否满意", content)
            # matchstf = re.search(r"联系人姓名：(.+?)联系人电话", content)
            resultstf = ""
            prefix2 = "客户是否满意："
            prefix_index2 = content.find(prefix2)
            # 如果找到了前缀，则提取前缀之后的内容
            if prefix_index2 != -1:
                resultstf = content[prefix_index2 + len(prefix2):]
                # print(resultstf)
            else:
                print("前缀未找到")
            # matchd = re.search(r"故障描述：(.+?)", content)
            # resultname, resulttel, resultclient, resultname2, resulttel2, resultlocation, results, resultt, resultd ="", "", "","", "", "","", "", ""
            resultrid = matchrid.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultrid)
            resultprc = matchprc.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultprc)
            resultname3 = matchname3.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultname3)
            resultif10 = matchif10.group(1)  # group(1) 捕获的是第一个括号内的内容，即姓名
            print(resultif10)
            print(resultstf)

            mfcontent = content.find("故障处理情况")
            lct2 = ""
            if mfcontent != -1:
                lct2 = content[:mfcontent].strip()
                print(lct2)
                # else:
                #     print("未找到目标字符串")
            file_path = r'D:\yidonbangon\Digitalrobot\2024-12\xlsx文件\{}报障.xlsx'.format(lct2)  # 替换为你的Excel文件路径
            current_datetime2 = datetime.now()
            # 格式化并打印当前时间
            mft_time2 = current_datetime2.strftime("%Y-%m-%d %H:%M:%S")
            workbook = openpyxl.load_workbook(file_path)
            # 选择工作表（假设工作表名为'Sheet1'，可以根据实际情况修改）
            sheet2 = workbook['Sheet1']
            resultrid1 = resultrid.strip()
            print(resultrid1)
            for idx2, row in enumerate(sheet2.iter_rows(min_row=1, max_col=1), start=1):
                print(f"Checking row {idx2}:{row[0].value}")
                if row[0].value == resultrid1:
                    print(f"Found '{resultrid1}' in row {idx2}")
            # for row in sheet2.iter_rows(min_row=1, max_col=1, values_only=True):
            #     if row[0] == resultrid1:
            #         # 获取当前行的行号
            #         row_num = row[0].row
            #         # 在B列中写入指定值value_b
                    sheet2.cell(row=idx2, column=12, value=resultprc)
                    sheet2.cell(row=idx2, column=13, value=resultname3)
                    sheet2.cell(row=idx2, column=14, value=resultif10)
                    sheet2.cell(row=idx2, column=15, value=resultstf)
                    sheet2.cell(row=idx2, column=16, value=mft_time2)
                    break  # 如果只需要找到第一个匹配项，则找到后退出循环
                else:
                    print("cantfind")
            # 保存修改后的Excel文件
            workbook.save(file_path)

            yidong = yidongOffice()
            yidong.findGroup(groupname)
            yidong.sendMsg("已将信息写入表格", person, "是", "群聊")
            yidong.findGroup("我的文件助手")
            print(f"数据已成功插入单元格中。")

        elif "晒单统计" in content:
            file = r'D:\yidonbangon\Digitalrobot\2024-12\xlsx文件\晒单统计.xlsx'
            sedFile(file)

        elif "晒单"in content:
            matchcons = re.search(r":(.+?)客户号码", content)
            matchnums = re.search(r"客户号码:(.+?)发展人", content)
            resultperson = ""
            prefixshow = "发展人:"
            prefix_indexshow = content.find(prefixshow)
            # 如果找到了前缀，则提取前缀之后的内容
            if prefix_indexshow != -1:
                resultperson = content[prefix_indexshow + len(prefixshow):]
                # print(resultshow)
            else:
                print("前缀未找到")
            nameshowp = content.find("晒单")
            nameshow = ""
            if nameshowp != -1:
                nameshow = content[:nameshowp].strip()
                # print(nameshow)
            print(nameshow)
            resultcons = matchcons.group(1)
            print(resultcons)
            resultnums = matchnums.group(1)
            print(resultnums)
            print(resultperson)
            file_path = r'D:\yidonbangon\Digitalrobot\2024-12\xlsx文件\晒单统计.xlsx'  # 替换为你的Excel文件路径
            current_datetimeshow = datetime.now()
            # 格式化并打印当前时间
            show_time = current_datetimeshow.strftime("%Y-%m-%d %H:%M:%S")
            keyword_columns = {
                "新入网": "F",
                "宽带": "G",
                "机顶盒": "H",
                "视频彩铃": "I",
                "移动APP": "J",
                "10分满意": "K",
                "和彩云": "L"
            }

            # # 检查文件是否存在，如果不存在则创建一个新的Excel文件
            # if not os.path.exists(excel_path):
            #     wb = Workbook()
            #     ws = wb.active
            #     wb.save(excel_path)
            #     print(f"创建新的Excel文件：{excel_path}")

            # 加载Excel文件
            # wb = openpyxl.load_workbook(excel_path)
            # ws = wb.active
            #
            # # 找到第一个空行
            # max_row = ws.max_row
            # next_row = max_row + 1


            workbook = openpyxl.load_workbook(file_path)
            # 选择工作表（假设工作表名为'Sheet1'，可以根据实际情况修改）
            sheetshow = workbook['Sheet1']
            empty_rowshow = None
            for idx, cell in enumerate(sheetshow['A'], start=1):  # 使用enumerate来获取行号，从1开始
                if cell.value is None:
                    empty_rowshow = idx
                    break
            if empty_rowshow is None:
                empty_rowshow = sheetshow.max_row + 1
            sheetshow[f'A{empty_rowshow}'] = nameshow
            sheetshow[f'B{empty_rowshow}'] = resultcons
            sheetshow[f'C{empty_rowshow}'] = resultnums
            sheetshow[f'D{empty_rowshow}'] = resultperson
            sheetshow[f'E{empty_rowshow}'] = show_time
            # 遍历关键字，检查字符串中是否存在
            for keyword, column in keyword_columns.items():
                if keyword in content:
                    # 在指定列写入“已办理”
                    sheetshow[f"{column}{empty_rowshow}"] = "已办理"
                    print(f"在{column}{empty_rowshow}写入'已办理'，关键字：{keyword}")
            workbook.save(file_path)  # 这将覆盖原始文件
            # 如果你不想覆盖原始文件，可以保存到一个新文件
            # wb.save('new_excel_file_with_data.xlsx')
            yidong = yidongOffice()
            yidong.findGroup(groupname)
            rpmsg = "已将信息写入表格"
            yidong.sendMsg(rpmsg, person, "是", "群聊")
            yidong.findGroup("我的文件助手")
            print(f"数据已成功插入单元格中。")

        elif "天气" in content:
            weather_msg = get_weather(content.replace("天气", ""))
            # wcf.send_text("@{} {}".format(nickName, weather_text), msg.roomid, msg.

            # weather_msg=""
            # weather_msg=get_weather("楚雄天气")
            yidong = yidongOffice()
            yidong.findGroup(groupname)
            yidong.sendMsg(weather_msg, person, "是", "群聊")
            # print("notincontent")
            # yidong = yidongOffice()
            # yidong.findGroup(groupname)
            # yidong.sendMsg("未识别成功", person, "是", "群聊")

        elif "网格签到" in content:
            matchsa = re.search(r"应到(.+?)人", content)
            matchaa = re.search(r"实到(.+?)人", content)
            wnamep = content.find("网格签到")
            wname = ""
            current_datetime3 = datetime.now()
            # 格式化并打印当前时间
            wa_time = current_datetime3.strftime("%Y-%m-%d %H:%M:%S")
            if wnamep != -1:
                wname = content[:wnamep].strip()
                print(wname)
            resultsa = matchsa.group(1)
            print(resultsa)
            resultaa = matchaa.group(1)
            print(resultaa)
            # mft_time = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
            file_path = r'D:\yidonbangon\Digitalrobot\2024-12\xlsx文件\签到情况统计表.xlsx'  # 替换为你的Excel文件路径
            wb = openpyxl.load_workbook(file_path)
            ws = wb['Sheet1']
            empty_row = None
            for idx, cell in enumerate(ws['A'], start=1):  # 使用enumerate来获取行号，从1开始
                if cell.value is None:
                    empty_row = idx
                    break
            if empty_row is None:
                empty_row = ws.max_row + 1
            ws[f'A{empty_row}'] = wname
            ws[f'B{empty_row}'] = resultsa
            # 在B列中的相应行（即A列空行的右侧一个单元格）输入数据
            ws[f'C{empty_row}'] = resultaa
            ws[f'D{empty_row}'] = wa_time
            ws[f'E{empty_row}'] = content
            wb.save(file_path)  # 这将覆盖原始文件
            # 如果你不想覆盖原始文件，可以保存到一个新文件
            # wb.save('new_excel_file_with_data.xlsx')
            yidong = yidongOffice()
            yidong.findGroup(groupname)
            rpmsg = "已将信息写入表格"
            yidong.sendMsg(rpmsg, person, "是", "群聊")
            yidong.findGroup("我的文件助手")
            print(f"数据已成功插入单元格中。")

        elif "签到情况统计" in content:
            file = r'D:\yidonbangon\Digitalrobot\2024-12\xlsx文件\签到情况统计表.xlsx'
            sedFile(file)

        # elif "网格签到"in content:
        #     matchsa = re.search(r"应到(.+?)人", content)
        #     matchaa = re.search(r"实到(.+?)人", content)
        #     wnamep= content.find("网格签到")
        #     wname = ""
        #     current_datetime3 = datetime.now()
        #     # 格式化并打印当前时间
        #     wa_time = current_datetime3.strftime("%Y-%m-%d %H:%M:%S")
        #     if wnamep != -1:
        #         wname = content[:wnamep].strip()
        #         print(wname)
        #     resultsa = matchsa.group(1)
        #     print(resultsa)
        #     resultaa = matchaa.group(1)
        #     print(resultaa)
        #     document = {
        #         "网格名": wname,
        #         "应到人数": resultsa,
        #         "实到人数": resultaa,
        #         "签到时间": wa_time,
        #         "原始消息": content
        #     }
        #
        #     # 插入单个文档
        #     result2 = collection2.insert_one(document)
        #     # 打印插入结果的_id
        #     print(f"Inserted document with _id: {result2.inserted_id}")
        #     # file_path = r'D:\pythonmini\testdata\签到情况统计表.xlsx'  # 替换为你的Excel文件路径
        #     # wb = openpyxl.load_workbook(file_path)
        #     # ws = wb['Sheet1']
        #     # empty_row = None
        #     # for idx, cell in enumerate(ws['A'], start=1):  # 使用enumerate来获取行号，从1开始
        #     #     if cell.value is None:
        #     #         empty_row = idx
        #     #         break
        #     # if empty_row is None:
        #     #     empty_row = ws.max_row + 1
        #     # ws[f'A{empty_row}'] = wname
        #     # ws[f'B{empty_row}'] = resultsa
        #     # # 在B列中的相应行（即A列空行的右侧一个单元格）输入数据
        #     # ws[f'C{empty_row}'] = resultaa
        #     # ws[f'D{empty_row}'] = wa_time
        #     # ws[f'E{empty_row}'] = content
        #     # wb.save(file_path)  # 这将覆盖原始文件
        #     # # 如果你不想覆盖原始文件，可以保存到一个新文件
        #     # # wb.save('new_excel_file_with_data.xlsx')
        #     yidong = yidongOffice()
        #     yidong.findGroup(groupname)
        #     rpmsg = "已将信息写入数据库"
        #     yidong.sendMsg(rpmsg, person, "是", "群聊")
        #     yidong.findGroup("我的文件助手")
        #     # print(f"数据已成功插入单元格中。")
        #
        # elif "签到情况统计" in content:
        #     try:
        #         # 查询集合中的所有文档
        #         documents1 = collection2.find()
        #
        #         # 初始化一个字符串变量来累加所有格式化的字符串
        #         full_string = ""
        #         yidong = yidongOffice()
        #         # 遍历并构建每个文档的格式化字符串
        #         for document1 in documents1:
        #             # 构建指定格式的字符串
        #             formatted_string = (
        #                 f"网格名: \"{document1.get('网格名', '未知')}\", "
        #                 f"应到人数: \"{document1.get('应到人数', '未知')}\", "
        #                 f"实到人数: \"{document1.get('实到人数', '未知')}\", "
        #                 f"签到时间: \"{document1.get('签到时间', '未知')}\"\n"
        #             )
        #             # 将格式化的字符串添加到累加字符串中
        #             full_string += formatted_string
        #
        #         # 遍历结束后，打印整个拼接后的字符串
        #         print(full_string)
        #         yidong.findGroup(groupname)
        #         yidong.sendMsg(full_string, person, "是", "群聊")
        #     except PyMongoError as e:
        #         print(f"An error occurred: {e}")



        # elif "169" in content:
        #     query = {"资费套餐": "169"}
        #     hm1=''
        #     # 查询结果，只返回 “详情” 字段
        #     results = collection.find(query, {"详情": 1, "_id": 0})  # 排除 _id 字段
        #
        #     # 输出 “详情” 字段的值
        #     for result in results:
        #         print(result.get("详情"))  # 使用 get 方法安全地获取 “详情” 字段的值
        #         hm1 = result.get("详情")
        #     # # set1 = connection()
        #     # hm1 = "1"
        #     # try:
        #     #     for x in test1.test1.find({"资费套餐": '169'}):
        #     #         hm1 = x.get("详情")
        #     #         if hm1 == None:
        #     #             hm1 = "2"
        #     #         elif hm1 != "":
        #     #             hm1 = "，套餐详情：{}".format(hm1)
        #     # except Exception as e:
        #     #     print(e,'169')
        #     # print(hm1)
        #     hm1 = "套餐详情：{}".format(hm1)
        #     yidong = yidongOffice()
        #     yidong.findGroup(groupname)
        #     yidong.sendMsg(hm1, person, "是", "群聊")
        #     # yidong.findGroup("我的文件助手")
        #
        # elif "139" in content:
        #     query = {"资费套餐": "139"}
        #     hm2 = ''
        #     # 查询结果，只返回 “详情” 字段
        #     results = collection.find(query, {"详情": 1, "_id": 0})  # 排除 _id 字段
        #
        #     # 输出 “详情” 字段的值
        #     for result in results:
        #         print(result.get("详情"))  # 使用 get 方法安全地获取 “详情” 字段的值
        #         hm2 = result.get("详情")
        #     hm2 = "套餐详情：{}".format(hm2)
        #     yidong = yidongOffice()
        #     yidong.findGroup(groupname)
        #     yidong.sendMsg(hm2, person, "是", "群聊")
        #     # yidong.findGroup("我的文件助手")
        #
        # elif "59+15" in content or "融合权益套餐" in content or "爱家会员" in content :
        #     query = {"资费套餐": "爱家会员"}
        #     hm3 = ''
        #     # 查询结果，只返回 “详情” 字段
        #     results = collection.find(query, {"详情": 1, "_id": 0})  # 排除 _id 字段
        #
        #     # 输出 “详情” 字段的值
        #     for result in results:
        #         print(result.get("详情"))  # 使用 get 方法安全地获取 “详情” 字段的值
        #         hm3 = result.get("详情")
        #     hm3 = "套餐详情：{}".format(hm3)
        #     yidong = yidongOffice()
        #     yidong.findGroup(groupname)
        #     yidong.sendMsg(hm3, person, "是", "群聊")
        #     # yidong.findGroup("我的文件助手")

        else:
            check_msg = check_excel(content)
            yidong = yidongOffice()
            yidong.findGroup(groupname)
            yidong.sendMsg(check_msg, person, "是", "群聊")

    except Exception as e:
        print(e)


def replyAtMsg(person, content, groupname):
    try:
        content1 = re.findall("@张晓明(.*)", content)[0]
        content2 = content1.strip()
        replyGroupMsg(person, content2, groupname)
        conlist0 = wins.ListItemControl().GroupControl(Depth=2).GetChildren()
        conlist = conlist0[1].GetChildren()[0]
        # conlist.Click()  # 点击第一个对话
    except Exception as e:
        print(e, 547)


def replyMsg(person, content):
    try:
        replyGroupMsg(person, content, groupname)
        conlist0 = wins.ListItemControl().GroupControl(Depth=2).GetChildren()
        conlist = conlist0[1].GetChildren()[0]
        conlist.Click()  # 点击第一个对话
    except Exception as e:
        print(e, 555)

def find_control_by_automation_id(control, target_id):
    # 检查当前控件的 AutomationId 是否匹配
    if control.AutomationId == target_id:
        return control

    # 遍历当前控件的所有子控件
    for child in control.GetChildren():
        # 递归调用函数，查找子控件中的匹配项
        result = find_control_by_automation_id(child, target_id)
        # 如果找到了匹配的控件，返回它
        if result:
            return result

    # 如果没有找到匹配的控件，返回 None
    return None


# 假设你已经通过某种方式获取到了根控件（可能是 WindowControl 或其他类型的控件）
# 注意：这里你需要根据实际情况设置正确的搜索条件和属性
# root_control = auto.DocumentControl(
#             ClassName='Chrome_RenderWidgetHostHWND', Name="移动办公")

# 检查根控件是否存在
# if root_control:
#     # 调用递归函数查找具有特定 AutomationId 的控件
#     target_control = find_control_by_automation_id(root_control, "group-name-span")
#
#     # 检查是否找到了目标控件
#     if target_control:
#         # 对 target_control 进行操作
#         print(f"找到了控件，Name: {target_control.Name}, ControlType: {target_control.ControlType}")
#         group1 = target_control.GetChildren()
#         groupname = group1[0].Name
#         print(groupname)
#         # ... 其他操作
#     else:
#         print("具有指定 AutomationId 的控件不存在")
# else:
#     print("根控件不存在")

aa = 0
while True:
    try:
        aa = aa + 1
        content, content1,  groupname= "", "", ""
        # flag = 0
        print("开始", aa)
        try:
            win = auto.DocumentControl(ClassName='Chrome_RenderWidgetHostHWND', Name="移动办公")
            # atMe = win.TextControl(Name="[有人@我]")
            # atMe.Click()
            getMsg = getNewmsgv2('张晓明')
            person = getMsg[0]
            content = getMsg[1]
            msgType = getMsg[2]
            # flag = getMsg[3]
            groupname = getMsg[3]
            print(person, msgType, groupname, aa)
            print(content)
            if "@张晓明" in content:
                replyAtMsg(person, content, groupname)
                # yidong.findGroup("我的文件助手")
            atMe = win.TextControl(Name="[有人@我]")
            atMe.Click()
        except Exception as e:
            print(e, 649)
    except Exception as e:
        print(e, 678)